package com.jdy.haoduoai.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PhotoItem;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageFetcher;
import com.jdy.haoduoai.util.IntentConstants;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.ycsj.goldmedalnewconcept.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

public class ImageZoomActivity2 extends BaseActivity {

  private ViewPager pager;
  private MyPageAdapter adapter;
  private int currentPosition;
//  private List<ImageItem> mDataList


  private ArrayList<PhotoItem> mDataList = new ArrayList<PhotoItem>();

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.act_zoom2);

    hideTitleView();

    initData();

    options = new DisplayImageOptions.Builder()
            .showImageOnFail(R.drawable.default_img_listitem) // 下载 失败 显示的 图片
            .cacheInMemory(true) // 缓存
            .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
            .build();
    // 创建默认的ImageLoader配置参数
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
            this).writeDebugLogs() // 打印 log 信息
            .build();
    ImageLoader.getInstance().init(configuration);

    ImageView photo_bt_share = (ImageView) findViewById(R.id.photo_bt_share);
    photo_bt_share.setVisibility(View.GONE);
    photo_bt_share.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    photo_bt_share.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent(ImageZoomActivity2.this,
                SharePopupWindow.class);
        intent.putExtra("pic", mDataList.get(currentPosition).url);
        intent.putExtra("sharepic", true);
        startActivity(intent);
      }
    });

    ImageView photo_bt_save = (ImageView) findViewById(R.id.photo_bt_save);
    photo_bt_save.setVisibility(View.GONE);
    photo_bt_save.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    photo_bt_save.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {

        if (mDataList.isEmpty() || mDataList.get(currentPosition) == null
                || Tools.isEmpty(mDataList.get(currentPosition).url)) {
          return;
        }

        showloading("");

        new AsyncTask<String, Void, Bitmap>() {
          @Override
          protected void onPostExecute(Bitmap result) {
            if (result != null) {
              String subForder = Environment.getExternalStorageDirectory()
                      .getAbsolutePath() + "/" + getPackageName();
              File foder = new File(subForder);
              if (!foder.exists()) {
                foder.mkdirs();
              }

              int indexx = mDataList.get(currentPosition).url.lastIndexOf("/");

              File myCaptureFile = new File(subForder, mDataList
                      .get(currentPosition).url.substring(indexx + 1));
              if (!myCaptureFile.exists()) {
                try {
                  myCaptureFile.createNewFile();
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
              BufferedOutputStream bos = null;
              try {
                bos = new BufferedOutputStream(new FileOutputStream(
                        myCaptureFile));
                result.compress(Bitmap.CompressFormat.JPEG, 80, bos);

                try {
                  MediaStore.Images.Media.insertImage(
                          getContentResolver(),
                          subForder
                                  + "/"
                                  + mDataList.get(currentPosition).url
                                  .substring(indexx + 1), "rtm.jpeg", null);
                } catch (FileNotFoundException e) {
                  e.printStackTrace();
                }
                Intent intent = new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(myCaptureFile);
                intent.setData(uri);
                sendBroadcast(intent);

                dismissLoading();

                ImageFetcher.getInstance(getApplicationContext()).hasBuildImagesBucketList = false;

                toastShow("已保存到相册");

              } catch (FileNotFoundException e) {
                e.printStackTrace();
              } finally {
                if (bos != null) {
                  try {
                    bos.flush();
                    bos.close();
                  } catch (IOException e) {
                    e.printStackTrace();
                  }
                }
              }
            }
          }

          @Override
          protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap resultImage = null;
            URL url;
            try {
              url = new URL(urldisplay);

              HttpURLConnection urlConnection = (HttpURLConnection) url
                      .openConnection();

              urlConnection.setRequestMethod("GET");
              urlConnection.connect();
              InputStream in = urlConnection.getInputStream();
              resultImage = BitmapFactory.decodeStream(in);
            } catch (MalformedURLException e) {
              e.printStackTrace();
            } catch (IOException e) {
              e.printStackTrace();
            }
            return resultImage;
          }
        }.execute(mDataList.get(currentPosition).url);
      }
    });

    findViewById(R.id.view_root).setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        finish();
      }
    });

    pager = (ViewPager) findViewById(R.id.viewpager);
    pager.setOnPageChangeListener(pageChangeListener);

    adapter = new MyPageAdapter(mDataList);
    pager.setAdapter(adapter);
    pager.setCurrentItem(currentPosition);
  }

  private DisplayImageOptions options;

  @SuppressWarnings("unchecked")
  private void initData() {
    currentPosition = getIntent().getIntExtra(
            IntentConstants.EXTRA_CURRENT_IMG_POSITION, 0);
    mDataList = (ArrayList<PhotoItem>) getIntent().getSerializableExtra(
            IntentConstants.EXTRA_IMAGE_LIST);

  }

  private void deleteCloudPhoto(final int pos) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, final ResponseResult arg0) {

        if (arg0.isSuccess()) {
          if (mDataList.size() == 1) {
            removeImgs();
            finish();
          } else {
            removeImg(currentPosition);
            pager.removeAllViews();
            adapter.removeView(currentPosition);
            adapter.notifyDataSetChanged();
          }
        } else {
          toastShow(arg0.data);
        }

        dismissLoading();
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);

        return HttpUtils.startRequest(HttpUtils.API_URL
                        + "/api/2.0/member/photocloud/" + mDataList.get(pos).id, param_,
                HttpUtils.TAG_DELETE_REQUEST);
      }
    }).execute();
  }

  private void removeImgs() {
    mDataList.clear();
  }

  private void removeImg(int location) {
    if (location + 1 <= mDataList.size()) {
      mDataList.remove(location);
    }
  }

  private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {

    @Override
    public void onPageSelected(int arg0) {
      currentPosition = arg0;
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }
  };

  class MyPageAdapter extends PagerAdapter {
    private List<PhotoItem> dataList = new ArrayList<PhotoItem>();
    private ArrayList<ImageView> mViews = new ArrayList<ImageView>();

    public MyPageAdapter(List<PhotoItem> dataList) {
      this.dataList = dataList;
      int size = dataList.size();
      for (int i = 0; i != size; i++) {
        ImageView iv = new ImageView(ImageZoomActivity2.this);

//        Picasso.with(ImageZoomActivity2.this).load(dataList.get(i).url)
//            .into(iv);

        if (Tools.isNotEmpty(dataList.get(i).url))
          ImageLoader.getInstance().displayImage(dataList.get(i).url, iv,
                  options);

        // ImageDisplayer.getInstance(ImageZoomActivity.this).displayBmp(iv,
        // null,
        // dataList.get(i).url, false);
        iv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        iv.setOnClickListener(new OnClickListener() {

          @Override
          public void onClick(View v) {
            finish();
          }
        });
        mViews.add(iv);
      }
    }

    @Override
    public int getItemPosition(Object object) {
      return POSITION_NONE;
    }

    @Override
    public Object instantiateItem(View arg0, int arg1) {
      ImageView iv = mViews.get(arg1);
      ((ViewPager) arg0).addView(iv);
      return iv;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
      if (mViews.size() >= arg1 + 1) {
        ((ViewPager) arg0).removeView(mViews.get(arg1));
      }
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
      return arg0 == arg1;
    }

    @Override
    public int getCount() {
      return dataList.size();
    }

    public void removeView(int position) {
      if (position + 1 <= mViews.size()) {
        mViews.remove(position);
      }
    }

  }
}